#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>

using namespace std;

#include "Log.hpp"

const int backlog = 10;

enum
{
    SOCKFD_ERR = 1,
    BIND_ERR,
    Listen_ERR
};

class Socket
{
public:
    Socket()
        : _sockfd(-1)
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "sockfd create fail,errno:%d,strerror:%s", errno, strerror(errno));
            exit(SOCKFD_ERR);
        }
    }

    void Bind(const uint16_t &port)
    {
        sockaddr_in sockin;
        sockin.sin_family = AF_INET;
        sockin.sin_port = htons(port);
        sockin.sin_addr.s_addr = INADDR_ANY;

        int res = bind(_sockfd, (sockaddr *)&sockin, sizeof(sockin));
        if (res < 0)
        {
            lg(Fatal, "bind create fail,errno:%d,strerror:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "listen error, %s: %d", strerror(errno), errno);
            exit(Listen_ERR);
        }
    }

    int Accept(string *ip, uint16_t *port)
    {
        sockaddr_in sockin;
        socklen_t len = sizeof(sockin);
        int sockfd = accept(_sockfd, (sockaddr *)&sockin, &len);
        if (sockfd < 0)
        {
            lg(Warning, "accept create fail,errno:%d,strerror:%s", errno, strerror(errno));
            return -1;
        }

        char buffer[1024];
        inet_ntop(AF_INET, &sockin.sin_addr, buffer, sizeof(buffer));

        *ip = buffer;
        *port = ntohs(sockin.sin_port);

        return sockfd;
    }

    bool Connect(const string &ip, const uint16_t port)
    {
        sockaddr_in sockin;
        memset(&sockin,0,sizeof(sockin));
        sockin.sin_family = AF_INET;
        sockin.sin_port = htons(port);
        inet_aton(ip.c_str(), &sockin.sin_addr);

        int res = connect(_sockfd, (sockaddr *)&sockin, sizeof(sockin));
        if (res < 0)
        {
            lg(Warning, "connect create fail,errno:%d,strerror:%s", errno, strerror(errno));
            return false;
        }

        return true;
    }

    void Close()
    {
        close(_sockfd);
    }

public:
    int _sockfd;
};